package com.example.chact;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.chact.adapter.MsgAdapter;
import com.example.chact.entity.Msg;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<Msg> msgList = new ArrayList<>();

    private EditText inputText;

    private Button send;

    private RecyclerView msgRecyclerView;

    private MsgAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initMsgs(); // 初始化消息

        //找到组件
        inputText = findViewById(R.id.input_text);
        send = findViewById(R.id.send);
        msgRecyclerView = findViewById(R.id.msg_recycle_view);

        //设置布局
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setLayoutManager(new LinearLayoutManager(this)); // 设置 RecyclerView 为线性布局, 默认时垂直方向
        msgRecyclerView.setAdapter(new MsgAdapter(msgList));

        //绑定事件
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputText.getText().toString();
                if (!"".equals(content)) {
                    Msg msg = new Msg(content, Msg.TYPE_SENT);
                    msgList.add(msg);
                    adapter.notifyItemInserted(msgList.size() - 1); // 当有新消息时刷新 RecycleView
                    msgRecyclerView.scrollToPosition(msgList.size() - 1); // 将 RecycleView 定位到最后一行
                    inputText.setText(""); // 清空输入框中的内容
                }
            }
        });
    }

    private void initMsgs() {
        Msg msg1 = new Msg("Hello guy.", Msg.TYPE_RECEIVED);
        Msg msg2 = new Msg("Hello. Who is that?", Msg.TYPE_SENT);
        Msg msg3 = new Msg("This is tom , nice to meet you.", Msg.TYPE_RECEIVED);

        msgList.add(msg1);
        msgList.add(msg2);
        msgList.add(msg3);
    }
}